<script setup>
import { computed } from 'vue'

const props = defineProps({
  // 数据相关
  data: {
    type: Array,
    default: () => []
  },
  columns: {
    type: Array,
    default: () => []
  },
  rowKey: String,

  // 样式相关
  stripe: Boolean,
  border: Boolean,
  size: {
    type: String,
    default: 'medium',
    validator: v => ['small', 'medium', 'large'].includes(v)
  },
  headerAlign: {
    type: String,
    default: 'left',
    validator: v => ['left', 'center', 'right'].includes(v)
  },
  cellAlign: {
    type: String,
    default: 'left',
    validator: v => ['left', 'center', 'right'].includes(v)
  }
})

defineEmits(['row-click'])

// 样式计算
const headerAlignClass = computed(() => `align-${props.headerAlign}`)
const cellAlignClass = computed(() => `align-${props.cellAlign}`)
</script>

<template>
  <div class="base-table" :class="[`table-size-${size}`, { 'table-stripe': stripe, 'table-border': border }]">
    <table>
      <thead>
        <tr>
          <th
            v-for="col in columns"
            :key="col.dataIndex"
            :class="[headerAlignClass]"
          >
            {{ col.title }}
          </th>
        </tr>
      </thead>
      <tbody>
        <tr
          v-for="(row, index) in data"
          :key="rowKey ? row[rowKey] : index"
          :class="{ 'stripe-row': stripe && index % 2 === 0 }"
          @click="$emit('row-click', row)"
        >
          <td
            v-for="col in columns"
            :key="col.dataIndex"
            :class="[cellAlignClass]"
          >
            <slot
              :name="`cell-${col.dataIndex}`"
              :row="row"
              :value="row[col.dataIndex]"
            >
              {{ row[col.dataIndex] }}
            </slot>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<style scoped>
.base-table {
  width: 100%;
  overflow-x: auto;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 12px;
  border-bottom: 1px solid #ebeef5;
}

/* 对齐样式 */
.align-left { text-align: left; }
.align-center { text-align: center; }
.align-right { text-align: right; }

/* 斑马纹 */
.stripe-row {
  background-color: #fafafa;
}

/* 边框 */
.table-border {
  border: 1px solid #ebeef5;
}
.table-border th,
.table-border td {
  border: 1px solid #ebeef5;
}

/* 尺寸 */
.table-size-small th,
.table-size-small td {
  padding: 8px;
}

.table-size-large th,
.table-size-large td {
  padding: 16px;
}

/* 悬停效果 */
tbody tr:hover {
  background-color: #f5f7fa;
}
</style>